package com.ohc.leetcode.二叉树.repect;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class 二叉树的层序遍历02 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return null;
        }
        queue.offer(root);
        List<Integer> list1 = null;
        while (!queue.isEmpty()) {   // 这一段可以进行遍历 其实有这最外层循坏就可以进行遍历。
            int len = queue.size();
            list1 = new ArrayList<>();
            while (len > 0) { // 记录每层的
                TreeNode node = queue.poll();
                list1.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                len--;
            }
            list.add(list1);
        }
        return list;
    }

    public static void main(String[] args) {

    }
}
